package com.vehiclemanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vehiclemanagement.entity.ETCCard;
import com.vehiclemanagement.entity.ETCCardRecharge;
import com.vehiclemanagement.mapper.ETCCardMapper;
import com.vehiclemanagement.mapper.ETCCardRechargeMapper;
import com.vehiclemanagement.service.ETCCardRechargeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * ETC卡充值记录服务实现类
 */
@Service
public class ETCCardRechargeServiceImpl extends ServiceImpl<ETCCardRechargeMapper, ETCCardRecharge> implements ETCCardRechargeService {

    @Autowired
    private ETCCardRechargeMapper etcCardRechargeMapper;
    
    @Autowired
    private ETCCardMapper etcCardMapper;

    @Override
    public IPage<ETCCardRecharge> pageRecharges(Integer current, Integer size, String searchTerm, 
                                              Long etcCardId, Integer status, 
                                              LocalDateTime startTime, LocalDateTime endTime) {
        // 创建分页对象
        Page<ETCCardRecharge> page = new Page<>(current, size);
        
        // 创建自定义SQL条件
        String whereSql = " r.del_flag = 0 ";
        
        // 添加搜索条件
        if (StringUtils.isNotBlank(searchTerm)) {
            whereSql += " AND (e.card_number LIKE '%" + searchTerm + "%' OR r.operator LIKE '%" + searchTerm + "%') ";
        }
        
        // 添加ETC卡ID查询条件
        if (etcCardId != null) {
            whereSql += " AND r.etc_card_id = " + etcCardId;
        }
        
        // 添加状态查询条件
        if (status != null) {
            whereSql += " AND r.status = " + status;
        }
        
        // 添加时间范围查询条件
        if (startTime != null) {
            whereSql += " AND r.recharge_time >= '" + startTime + "'";
        }
        
        if (endTime != null) {
            whereSql += " AND r.recharge_time <= '" + endTime + "'";
        }
        
        // 添加排序
        whereSql += " ORDER BY r.recharge_time DESC";
        
        System.out.println("执行查询SQL条件: " + whereSql);
        
        // 执行查询
        return etcCardRechargeMapper.selectPageWithInfo(page, whereSql);
    }

    @Override
    public ETCCardRecharge getRechargeById(Long id) {
        return etcCardRechargeMapper.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addRecharge(ETCCardRecharge recharge) {
        System.out.println("服务层开始添加ETC卡充值记录: " + recharge);
        
        try {
            // 设置默认值
            if (recharge.getRechargeTime() == null) {
                recharge.setRechargeTime(LocalDateTime.now());
            }
            if (recharge.getCreateTime() == null) {
                recharge.setCreateTime(LocalDateTime.now());
            }
            if (recharge.getUpdateTime() == null) {
                recharge.setUpdateTime(LocalDateTime.now());
            }
            if (recharge.getDelFlag() == null) {
                recharge.setDelFlag(0);
            }
            if (recharge.getStatus() == null) {
                recharge.setStatus(1); // 默认成功
            }
            
            // 先插入充值记录
            int result = etcCardRechargeMapper.insert(recharge);
            
            // 如果充值成功，更新ETC卡余额
            if (result > 0 && recharge.getStatus() == 1) {
                ETCCard etcCard = etcCardMapper.selectById(recharge.getEtcCardId());
                if (etcCard != null) {
                    // 更新余额
                    BigDecimal newBalance = etcCard.getBalance().add(recharge.getAmount());
                    etcCard.setBalance(newBalance);
                    etcCard.setUpdateTime(LocalDateTime.now());
                    
                    etcCardMapper.updateById(etcCard);
                    System.out.println("更新ETC卡余额成功，卡号: " + etcCard.getCardNumber() + ", 新余额: " + newBalance);
                }
            }
            
            System.out.println("插入结果: " + result + ", 生成的ID: " + recharge.getId());
            
            return result > 0;
        } catch (Exception e) {
            System.err.println("添加ETC卡充值记录发生异常: " + e.getMessage());
            e.printStackTrace();
            throw e; // 抛出异常以触发事务回滚
        }
    }

    @Override
    public boolean updateRecharge(ETCCardRecharge recharge) {
        // 更新时间
        recharge.setUpdateTime(LocalDateTime.now());
        
        return etcCardRechargeMapper.updateById(recharge) > 0;
    }

    @Override
    public boolean deleteRecharge(Long id) {
        // 使用物理删除
        System.out.println("执行物理删除ETC卡充值记录，ID: " + id);
        
        try {
            // 直接物理删除记录
            int result = etcCardRechargeMapper.deletePhysically(id);
            System.out.println("物理删除结果: " + result);
            return result > 0;
        } catch (Exception e) {
            System.err.println("删除ETC卡充值记录时出错: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public BigDecimal getTotalRechargeAmount(Long etcCardId) {
        return etcCardRechargeMapper.getTotalRechargeAmount(etcCardId);
    }

    @Override
    public List<ETCCardRecharge> getRechargesByETCCardId(Long etcCardId) {
        LambdaQueryWrapper<ETCCardRecharge> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ETCCardRecharge::getEtcCardId, etcCardId)
                  .eq(ETCCardRecharge::getDelFlag, 0)
                  .orderByDesc(ETCCardRecharge::getRechargeTime);
        
        return etcCardRechargeMapper.selectList(queryWrapper);
    }
} 